package com.shark.teach;

/**
 * @auther shark
 * @create 2024-08-06 21:41
 */
public class VolatileOrderDemo
{
    static  int a;
    static  int b;
    static int x;
    static int y;

    public static void main(String[] args) throws InterruptedException
    {
        int i = 0;//计数器，

        while (true)
        {
            i++;

            a = b = x = y = 0;

            Thread thread1 = new Thread(() -> {
                a = 1;
                x = b;
            });

            Thread thread2 = new Thread(() -> {
                b = 1;
                y = a;
            });

            thread1.start();
            thread2.start();

            thread1.join();
            thread2.join();

            System.out.println("第" + i + "次打印：x=" + x + ", y=" + y);//x=0,y = 1;  顺序正常

            if (x == 0 && y == 0){
                break;
            }
        }
    }

}
